package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrdersDetailMapper ordersDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShopCartMapper shopCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    @Transactional//保持事务一致性
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        /** 1----
         * 判断前端提交过来的订单是否有地址缺失
         */
        Long userId = BaseContext.getCurrentId();
        if(ordersSubmitDTO.getAddressBookId() ==null){
            throw  new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        AddressBook addressBook = addressBookMapper.getAddressBookById(userId);


        /** 2----
         * 判断购物车数据是否为空
         */
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shopCartMapper.getShopCart(shoppingCart);//获取购物车数据
        if (list.size() == 0 || list == null) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
            //购物车为空 无法下单
        }

        /** 3----
         * 插入订单表
         */
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);//属性拷贝
        orders.setUserId(userId);//设置用户id
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号--时间戳生成
        orders.setAddress(addressBook.getDetail());//设置订单地址
        orders.setPayStatus(Orders.UN_PAID);//订单支付状态;
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//用户电话

        orderMapper.insert(orders);//插入订单表

        /** 4----
         * 插入订单明细表
         */
        List<OrderDetail> orderDetaillist = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());//设置订单id
            orderDetaillist.add(orderDetail);
        }

        //批量插入订单明细表
        ordersDetailMapper.insertBach(orderDetaillist);

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().
                id(orders.getId()).
                orderAmount(orders.getAmount()).
                orderNumber(orders.getNumber()).
                orderTime(orders.getOrderTime()).build();

        //清空购物车
        shopCartMapper.deleteShoppingCart(userId);

        return orderSubmitVO;
    }


    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getUser(userId);

        //调用微信支付接口，生成预支付交易单
       /* JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/
        //生成JSONObject对象 跳过 支付流程
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }


    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getnNmber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .number(ordersDB.getNumber())
                .build();

        orderMapper.change(orders);

        HashMap map = new HashMap();
        map.put("orderId",ordersDB.getId());
        map.put("type",1);
        map.put("content","订单号"+ordersDB.getNumber());

        String json = JSON.toJSONString(map);

        //websocket发送到前端服务器
        webSocketServer.sendToAllClient(json);

    }

    @Override
    public void repetition(Long id) {

        //获取原来的订单数据
        Orders order = orderMapper.getOrder(id);

        order.setUserId(BaseContext.getCurrentId());//设置用户id
        order.setOrderTime(LocalDateTime.now());//下单时间
        order.setNumber(String.valueOf(System.currentTimeMillis()));//订单号--时间戳生成
        AddressBook addressBook = addressBookMapper.getAddressBookById(BaseContext.getCurrentId());
        order.setAddress(addressBook.getDetail());//设置订单地址
        order.setPayStatus(Orders.UN_PAID);//订单支付状态;
        order.setStatus(Orders.PENDING_PAYMENT);//订单状态
        order.setConsignee(addressBook.getConsignee());//收货人
        order.setPhone(addressBook.getPhone());//用户电话

        orderMapper.insert(order);//插入订单表

        List<OrderDetail> orderDetaillist = ordersDetailMapper.getByOrderId(order.getId()-1);
        for (OrderDetail orderDetail : orderDetaillist) {
            orderDetail.setOrderId(order.getId());
        }

        //批量插入订单明细表
        ordersDetailMapper.insertBach(orderDetaillist);

    }

    @Override
    public void reminder(Long id) {

        Orders order = orderMapper.getOrder(id);

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+order.getNumber());

        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);

    }

    /**
     * 接单Impl
     * @param
     */
    @Override
    public void accept(OrdersConfirmDTO ordersConfirmDTO) {

        //接单后更改订单状态为-已接单
        orderMapper.update(ordersConfirmDTO);

    }


    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {

        orderMapper.delivery(id);

    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void finish(Long id) {


        //提前设置订单完成时间

        LocalDateTime check_out_time = LocalDateTime.now();

        orderMapper.finish(id,check_out_time);
    }

    /**
     * 取消订单
     * @param
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {

        //取消订单 更改订单表订单状态 以及添加拒绝原因
        orderMapper.cancel(ordersCancelDTO);


    }


    /**
     * 拒绝订单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {

        orderMapper.rejection(ordersRejectionDTO);

    }

    @Override
    public Orders detail(Long id) {

        Orders orders = orderMapper.detail(id);
        return orders;

    }

    @Override
    public PageResult historyOrders(int pageNum, int pageSize, Integer status) {

        //开启分页查询
//        PageHelper.startPage(pageNum,pageSize);
//
//        //获取订单id
//        Page<Long> list = orderMapper.getId(BaseContext.getCurrentId());
//
//        List<OrderVO> orderVOList = new ArrayList<>();
//
//        for (Long order_id : list) {
//            OrderVO orderVO = new OrderVO();
//            //通过每一条订单id查询对应的订单明细表
//            List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(order_id);
//            Orders orders = orderMapper.getAllorders(order_id);
//            orderVO.setOrderDetailList(orderDetailList);
//            BeanUtils.copyProperties(orders,orderVO);
//            orderVOList.add(orderVO);
//        }


        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = ordersDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);
        //return new PageResult(list.getTotal(), orderVOList);
    }

    @Override
    public OrderVO orderdetail(Long id) {

        //查看订单详情

        //订单明细表
        List<OrderDetail> orderDetail = orderMapper.getdetatil(id);

        OrderVO orderVO = new OrderVO();
        orderVO.setOrderDetailList(orderDetail);


        //获取订单数据
        Orders order = orderMapper.getOrder(id);
        BeanUtils.copyProperties(order,orderVO);

        return orderVO;

    }


    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.conditionSerch(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);

    }

    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }


    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }


    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


}
